# 模拟请求
#
# 使用方法:
# 1. 先启动Flask服务: python main.py
# 2. 运行刺激提取测试: python test.py <视频路径> [亮度阈值]
# 3. 运行刺激参数输入测试: python test2.py params
#
# 示例:
# python test.py E:\videos\test.mp4 150  # 运行视频刺激提取测试
# python test2.py params                 # 运行刺激参数输入测试

import requests
import json
import time
import os
import sys
from urllib.parse import urljoin
import webbrowser

# 服务基础URL
BASE_URL = "http://127.0.0.1:5020"

def test_stimulus_extraction(video_path, threshold=150):
    """
    测试视频刺激提取功能
    
    Args:
        video_path: 视频文件路径
        threshold: 亮度阈值，默认150
    """
    print(f"测试视频刺激提取: {video_path}, 阈值: {threshold}")
    
    # 确保视频文件存在
    if not os.path.exists(video_path):
        print(f"错误: 视频文件不存在: {video_path}")
        return

    # 步骤1: 发送提取请求
    try:
        response = requests.post(
            urljoin(BASE_URL, "/task/extract_stimulus"),
            json=[video_path, threshold]
        )
        response.raise_for_status()
    except Exception as e:
        print(f"请求失败: {e}")
        return
    
    # 获取任务信息
    task_info = response.json()
    print(f"任务创建成功，ID: {task_info['task_id']}")
    
    # 步骤2: 打开UI页面让用户选择点
    ui_url = urljoin(BASE_URL, task_info['ui_addr'])
    # ui_url = task_info['ui_addr']
    print(f"请在打开的浏览器窗口中选择LED点位置...")
    webbrowser.open(ui_url)
    
    # 步骤3: 等待处理完成
    progress_url = urljoin(BASE_URL, task_info['progress_pipe_addr'])
    result_url = urljoin(BASE_URL, task_info['result_addr'])
    # progress_url = task_info['progress_pipe_addr']
    # result_url = task_info['result_addr']
    
    print("等待处理完成...")
    while True:
        try:
            progress_response = requests.get(progress_url)
            progress_data = progress_response.json()
            
            # 如果出错
            if "error" in progress_data and progress_data["error"]:
                print(f"处理出错: {progress_data['error']}")
                return
                
            # 打印进度
            if progress_data["status"] == "Running":
                sys.stdout.write(f"\r进度: {progress_data['percentage']}%")
                sys.stdout.flush()
            
            # 如果完成
            if progress_data["status"] == "Completed":
                print("\n处理完成!")
                break
                
            time.sleep(1)
        except Exception as e:
            print(f"\n获取进度失败: {e}")
            time.sleep(2)
    
    # 步骤4: 获取结果
    try:
        result_response = requests.get(result_url)
        result_data = result_response.json()
        
        # 打印结果摘要
        stimulus_frames = result_data
        print(f"共找到 {len(stimulus_frames)} 个刺激帧")
        
        if stimulus_frames:
            print(f"前10个刺激帧: {stimulus_frames[:10]}")
            
        # 保存结果到文件
        result_file = "stimulus_result.json"
        with open(result_file, "w") as f:
            json.dump(result_data, f, indent=2)
        print(f"完整结果已保存到: {result_file}")
        
    except Exception as e:
        print(f"获取结果失败: {e}")
        import traceback
        traceback.print_exc()


def test_stimulus_extraction_standalone(video_path, threshold=150):
    """
    测试视频刺激提取功能
    
    Args:
        video_path: 视频文件路径
        threshold: 亮度阈值，默认150
    """
    print(f"测试视频刺激提取: {video_path}, 阈值: {threshold}")
    
    # 确保视频文件存在
    if not os.path.exists(video_path):
        print(f"错误: 视频文件不存在: {video_path}")
        return

    # 步骤1: 发送提取请求
    try:
        response = requests.post(
            urljoin(BASE_URL, "/task/extract_stimulus"),
            json=[video_path, threshold]
        )
        response.raise_for_status()
    except Exception as e:
        print(f"请求失败: {e}")
        return
    
    # 获取任务信息
    task_info = response.json()
    print(f"任务创建成功，ID: {task_info['task_id']}")

if __name__ == "__main__":
    # 测试视频刺激提取
    video_path = r"C:\Users\songy\Desktop\fyp-songy-2025-05-17\videos\fyp_20250331103458.mp4"  # 默认视频路径
    threshold = 150  # 默认亮度阈值
    
    video_path = sys.argv[1] if len(sys.argv) > 1 else video_path
    threshold = int(sys.argv[2]) if len(sys.argv) > 2 else threshold
    
    print(f"使用视频: {video_path}, 阈值: {threshold}")
    test_stimulus_extraction(video_path, threshold)

